package com.winter.common;

//import org.slf4j.Logger;
import org.apache.commons.lang3.StringUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * 对jedis简单封装类
 */
public class JedisTemplate {

    private JedisPool jedisPool;

    public JedisTemplate(JedisPool jedisPool) {
        this.jedisPool = jedisPool;
    }

    // private final Logger logger = LoggerFactory.getLogger(JedisTemplate.class);

    /**
     * 设置set key value处理
     * 
     * @param key 设置的key
     * @param value 设置的value值
     * @param expiredSecs 失效时间，单位为秒，从设置的时间开始往后推算处理
     */
    public void set(String key, String value, int expiredSecs) {
        if (StringUtils.isNotEmpty(key) && StringUtils.isNotEmpty(value)) {
            JedisPool jedisPool = null;
            Jedis jedis = null;
            try {
                jedisPool = getJedisPool();
                if (jedisPool != null) {
                    jedis = jedisPool.getResource();
                    jedis.setex(key, expiredSecs, value);
                    //logger.info("jedisTemplate>>>set key={},value={},expiredSecs={} succeed", new Object[] { key, value, expiredSecs });
                }
            } catch (Exception e) {
                if (jedisPool != null) {
                    jedisPool.returnBrokenResource(jedis);
                }
//                logger.error(String.format("jedisTemplate>>>set key=%s,value=%s,expiredSecs=%s failed e=%s", new Object[] { key, value, expiredSecs, e.getCause() }), e);
            } finally {
                if (jedisPool != null) {
                    jedisPool.returnResource(jedis);
                }
            }
        }
    }

    /**
     * 设置set key value 默认不设定失效时间
     * 
     * @param key
     * @param value
     */
    public void set(String key, String value) {
        if (StringUtils.isNotEmpty(key) && StringUtils.isNotEmpty(value)) {
            JedisPool jedisPool = null;
            Jedis jedis = null;
            try {
                jedisPool = getJedisPool();
                if (jedisPool != null) {
                    jedis = jedisPool.getResource();
                    jedis.set(key, value);
                    //logger.info("jedisTemplate>>>set key={},value={} succeed", new Object[] { key, value });
                }
            } catch (Exception e) {
                if (jedisPool != null) {
                    jedisPool.returnBrokenResource(jedis);
                }
                //logger.error(String.format("jedisTemplate>>>set key=%s,value=%s failed e=%s", new Object[] { key, value, e.getCause() }),e);
            } finally {
                if (jedisPool != null) {
                    jedisPool.returnResource(jedis);
                }
            }
        }
    }

    /**
     * 删除key
     * 
     * @param key
     */
    public void del(String key) {
        if (StringUtils.isNotEmpty(key)) {
            JedisPool jedisPool = null;
            Jedis jedis = null;
            try {
                jedisPool = getJedisPool();
                if (jedisPool != null) {
                    jedis = jedisPool.getResource();

                    jedis.del(key);
                    //logger.info("jedisTemplate>>>delete key={},succeed", new Object[] { key });
                }
            } catch (Exception e) {
                if (jedisPool != null) {
                    jedisPool.returnBrokenResource(jedis);
                }
                //logger.error(String.format("jedisTemplate>>>delete key=%s,failed e=%s", new Object[] { key, e.getCause() }), e);
            } finally {
                if (jedisPool != null) {
                    jedisPool.returnResource(jedis);
                }
            }
        }
    }

    /**
     * 根据key查询value值
     * 
     * @param key
     * @return
     */
    public String get(String key) {
        String value = "";
        if (StringUtils.isNotEmpty(key)) {
            JedisPool jedisPool = null;
            Jedis jedis = null;
            try {
                jedisPool = getJedisPool();
                if (jedisPool != null) {
                    jedis = jedisPool.getResource();
                    String tmp = jedis.get(key);
                    value = tmp != null ? tmp : value;
                    // logger.info("jedisTemplate>>>get key={},value={} succeed", new Object[] { key, value });
                }
            } catch (Exception e) {
                if (jedisPool != null) {
                    jedisPool.returnBrokenResource(jedis);
                }
                // logger.error(String.format("jedisTemplate>>>get key=%s,value=%s failed e=%s", new Object[] { key, value, e.getCause() }), e);
            } finally {
                if (jedisPool != null) {
                    jedisPool.returnResource(jedis);
                }
            }
        }
        return value;
    }

    /**
     * 设置hset,key-fieldKey-value值
     * 
     * @param key
     * @param fieldKey
     * @param value
     */
    public void hset(String key, String fieldKey, String value) {
        if (StringUtils.isNotEmpty(key) && StringUtils.isNotEmpty(value) && StringUtils.isNotEmpty(fieldKey)) {
            JedisPool jedisPool = null;
            Jedis jedis = null;
            try {
                jedisPool = getJedisPool();
                if (jedisPool != null) {
                    jedis = jedisPool.getResource();
                    jedis.hset(key, fieldKey, value);

                    //logger.info("jedisTemplate>>>hset key={},fieldKey={},value={} succeed", new Object[] { key, fieldKey, value });
                }
            } catch (Exception e) {
                if (jedisPool != null) {
                    jedisPool.returnBrokenResource(jedis);
                }
                //logger.error(String.format("jedisTemplate>>>hset key=%s,fieldKey=%s,value=%s failed e=%s", new Object[] { key, fieldKey, value, e.getCause() }), e);
            } finally {
                if (jedisPool != null) {
                    jedisPool.returnResource(jedis);
                }
            }
        }
    }

    /**
     * 删除hdelete方法
     * 
     * @param key
     * @param fieldKey
     */
    public void hdel(String key, String fieldKey) {
        if (StringUtils.isNotEmpty(key) && StringUtils.isNotEmpty(fieldKey)) {
            JedisPool jedisPool = null;
            Jedis jedis = null;
            try {
                jedisPool = getJedisPool();
                if (jedisPool != null) {
                    jedis = jedisPool.getResource();

                    jedis.hdel(key, fieldKey);
                    //logger.info("jedisTemplate>>>hdelete key={},fieldKey={} succeed", new Object[] { key, fieldKey });
                }
            } catch (Exception e) {
                if (jedisPool != null) {
                    jedisPool.returnBrokenResource(jedis);
                }
                // logger.error(String.format("jedisTemplate>>>hset key=%s,fieldKey=%s failed e=%s", new Object[] { key, fieldKey, e.getCause() }), e);
            } finally {
                if (jedisPool != null) {
                    jedisPool.returnResource(jedis);
                }
            }
        }
    }

    /**
     * 获取hgetall key对应的值，放在map<fieldKey,value>中返回
     * 
     * @param key
     * @return
     */
    public Map<String, String> hgetAll(String key) {
        Map<String, String> map = new HashMap<String, String>();
        if (StringUtils.isNotEmpty(key)) {
            JedisPool jedisPool = null;
            Jedis jedis = null;
            try {
                jedisPool = getJedisPool();
                if (jedisPool != null) {
                    jedis = jedisPool.getResource();
                    Map<String, String> tmpmap = jedis.hgetAll(key);
                    map = tmpmap != null ? tmpmap : map;
                    //logger.info("jedisTemplate>>>hgetall key={},value={} succeed", new Object[] { key, tmpmap });
                }
            } catch (Exception e) {
                if (jedisPool != null) {
                    jedisPool.returnBrokenResource(jedis);
                }
                // logger.error(String.format("jedisTemplate>>>hget key=%s,value=%s,failed e=%s", new Object[] { key, map, e.getCause() }), e);
            } finally {
                if (jedisPool != null) {
                    jedisPool.returnResource(jedis);
                }
            }
        }
        return map;
    }

    /**
     * 查询匹配keys全部key键值列表
     * 
     * @param keysPattern redis里边的keys* 命令
     * @return
     */
    public Set<String> keys(String keysPattern) {
        Set<String> set = new HashSet<String>();
        if (StringUtils.isNotEmpty(keysPattern)) {
            JedisPool jedisPool = null;
            Jedis jedis = null;
            try {
                jedisPool = getJedisPool();
                if (jedisPool != null) {
                    jedis = jedisPool.getResource();
                    Set<String> tmp = jedis.keys(keysPattern);
                    set = tmp != null ? tmp : set;
                    // logger.info("jedisTemplate>>>keys keyPattern={}, set.size={}", new Object[] { keysPattern, set.size() });
                }
            } catch (Exception e) {
                if (jedisPool != null) {
                    jedisPool.returnBrokenResource(jedis);
                }
                // logger.error(String.format("jedisTemplate>>>keys keyPattern=%s, failed e=%s", new Object[] { keysPattern, e.getCause() }),e);
            } finally {
                if (jedisPool != null) {
                    jedisPool.returnResource(jedis);
                }
            }
        }
        return set;
    }

    /**
     * 从hset中hget出对应的key-field对应的value值
     * 
     * @param key
     * @param fieldKey
     * @return
     */
    public String hget(String key, String fieldKey) {
        String value = "";
        if (StringUtils.isNotEmpty(key) && StringUtils.isNotEmpty(fieldKey)) {
            JedisPool jedisPool = null;
            Jedis jedis = null;
            try {
                jedisPool = getJedisPool();
                if (jedisPool != null) {
                    jedis = jedisPool.getResource();
                    String tmp = jedis.hget(key, fieldKey);
                    value = tmp != null ? tmp : value;
                    //logger.info("jedisTemplate>>>hget key={},fieldKey={},value={} succeed", new Object[] { key, fieldKey, value });
                }
            } catch (Exception e) {
                if (jedisPool != null) {
                    jedisPool.returnBrokenResource(jedis);
                }
                // logger.error(String.format("jedisTemplate>>>hget key=%s,fieldKey=%s,value=%s failed e=%s", new Object[] { key, fieldKey, value, e.getCause() }),e);
            } finally {
                if (jedisPool != null) {
                    jedisPool.returnResource(jedis);
                }
            }
        }
        return value;
    }

    public JedisPool getJedisPool() {
        return jedisPool;
    }

    public void setJedisPool(JedisPool jedisPool) {
        this.jedisPool = jedisPool;
    }

}